package com.boot;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class MyClassLoader extends ClassLoader {

	
	private String name;
	private String path;
	private final String fileType = ".class";
	
	public MyClassLoader(String name) {
		super();
		this.name = name;
	}
	
	public MyClassLoader(ClassLoader parent, String name) {
		super(parent);
		this.name = name;
	}
	
	@Override
	public String toString() {
		return this.name;
	}
	
	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}
	
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		
		System.out.println("try to load class:" + name);
		
		byte[] data = loadClassDate(name);
		
		data = decodeClassData(data);
		
		return this.defineClass(name, data, 0, data.length);
	}
	
	private byte[] decodeClassData(byte[] data){
		return ClassSecurity.decode(data);
	}
	
	private byte[] loadClassDate(String name){
		InputStream in = null;
		byte[] data = null;
		
		ByteArrayOutputStream baos = null;
		
		try {
			
			name = name.replace(".", "\\");
			
			in = new BufferedInputStream(new FileInputStream(new File(path + name + fileType)));
			baos = new ByteArrayOutputStream();
			
			int ch = 0;
			
			while ((ch = in.read()) != -1) {
				baos.write(ch);
			}
			
			data = baos.toByteArray();
					
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			} finally {
				try {
					baos.close();
				} catch (Exception e3) {
					e3.printStackTrace();
				}
			}
		}
		return data;
	}
	
	
}
